# -*- coding: UTF-8 -*-
# 2023/11/26 23:27
import configparser
import os

from tools.get_logger import get_logger

loger = get_logger()


class my_configer:
    def __init__(self, config_path="./config.ini"):
        self.confer = configparser.ConfigParser()
        self.config_path = config_path
        self.init_config()

    def init_config(self):

        if os.path.isfile(self.config_path):
            self.confer.read(self.config_path)

        else:
            loger.info(f"未创建配置文件,新增默认配置")
            # 设置默认配置
            # 设置默认值,并保存
            self.add_section("main")
            self.add_section("computer")
            self.add_section("phone")
            self.add_main_option("style", "cyborg")

            # 保存配置文件
            self.save_config()

    def sections(self):
        """
        获取所有sections
        """
        return self.confer.sections()

    def options(self, section):
        """
        返回给定给定section下options的值
        """
        return self.confer.options(section)

    def items(self, section):
        """
        以键值对形式返回给定给定section下options的值
        """
        return self.confer.items(section)

    def get(self, section, options):
        """
        返回给定给定section下options的值
        """
        return self.confer.get(section, options)

    def get_main_option(self, options):
        return self.get("main", options)

    def get_computer_option(self, options):
        return self.get("computer", options)

    def get_phone_option(self, options):
        return self.get("phone", options)

    def add_section(self, section):
        """
        给配置添加指定section
        """
        self.confer.add_section(section)
        self.save_config()

    def set(self, section, option, value):
        """
        在指定section下的option设置值
        """
        if not self.has_section(section):
            self.add_section(section)

        self.confer.set(section, option, value)
        self.save_config()

    def add_main_option(self, option, value):
        self.set("main", option, value)

    def add_computer_option(self, option, value):
        self.set("computer", option, value)

    def add_phone_option(self, option, value):
        self.set("phone", option, value)

    def has_section(self, section):
        """
        获取是否包含指定的section
        """
        return self.confer.has_section(section)

    def remove_option(self, section, option):
        """
        从指定的部分中删除指定的选项
        如果该部分不存在，抛出NoSectionError。如果存在的选项被删除，返回True;否则返回False
        """
        return self.confer.remove_option(section, option)

    def remove_section(self, section):
        """
        从配置中删除指定的section
        如果这个部分确实存在，返回True。否则返回False
        """
        self.confer.remove_section(section)

    def save_config(self):
        """
        把配置写入文件
        """
        # 将修改后的配置数据写回到文件中
        with open(self.config_path, "w") as configfile:
            self.confer.write(configfile)
